<template>
  <div class="users-container">
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path:'/home'}">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card class="box-card">
      <!-- 功能区域 -->
      <el-row :gutter="20">
        <!-- 根据id搜索 -->
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="initUserList">
            <el-button slot="append" icon="el-icon-search" @click="initUserList"></el-button>
          </el-input>
        </el-col>
        <!-- 添加用户 -->
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
          <!-- 添加用户对话框 -->
          <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" :before-close="handleClose"
            @close="addClearDialog">
            <!-- 对话框主体 -->
            <el-form :model="postInfo" :rules="rules" ref="postInfoRef" label-width="70px">
              <el-form-item label="用户名" prop="username">
                <el-input v-model="postInfo.username"></el-input>
              </el-form-item>
              <el-form-item label="密码" prop="password">
                <el-input v-model="postInfo.password"></el-input>
              </el-form-item>
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="postInfo.email"></el-input>
              </el-form-item>
              <el-form-item label="手机" prop="mobile">
                <el-input v-model="postInfo.mobile"></el-input>
              </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button @click="addDialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="addUser">确 定</el-button>
            </span>
          </el-dialog>
          <!-- 修改用户信息对话框 -->
          <el-dialog title="修改用户信息" :visible.sync="editDialogVisible" width="50%" :before-close="handleClose"
            @close="editClearDialog">
            <!-- 对话框主体 -->
            <el-form :model="editInfo" :rules="rules" ref="editInfoRef" label-width="70px">
              <el-form-item label="用户名">
                <el-input v-model="editInfo.username" :disabled="true"></el-input>
              </el-form-item>
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="editInfo.email"></el-input>
              </el-form-item>
              <el-form-item label="手机" prop="mobile">
                <el-input v-model="editInfo.mobile"></el-input>
              </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
              <el-button @click="editDialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="editUser">确 定</el-button>
            </span>
          </el-dialog>
          <!-- 设置分配角色对话框 -->
          <el-dialog title="分配角色" :visible.sync="settingDialogVisible" width="50%" :before-close="handleClose"
            @close="settingClearDialog">
            <!-- 对话框主体 -->
            <p>当前的用户：{{settingInfo.username}}</p>
            <p>当前的角色：{{settingInfo.role_name}}</p>
            <p>
              分配新角色：
              <el-select v-model="selectedRoleId" placeholder="请选择">
                <el-option v-for="item in rolesList" :key="item.id" :label="item.roleName" :value="item.id">
                </el-option>
              </el-select>
            </p>
            <span slot="footer" class="dialog-footer">
              <el-button @click="settingDialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="saveRole">确 定</el-button>
            </span>
          </el-dialog>
        </el-col>
      </el-row>
      <br>
      <!-- 用户列表区域 -->
      <el-table :data="info" border style="width: 100%">
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="userStateChange(scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-tooltip effect="dark" content="编辑" placement="top">
              <el-button type="primary" icon="el-icon-edit" circle @click="openEditUser(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip effect="dark" content="分配角色" placement="top">
              <el-button type="warning" icon="el-icon-setting" circle @click="openSettingRole(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip effect="dark" content="删除" placement="top">
              <el-button type="danger" icon="el-icon-delete" circle @click="deleteUser(scope.row.id)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum" :page-sizes="[1, 2, 5, 10]" :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </el-card>
  </div>
</template>
<script>
  export default {
    name: 'MyUsers',
    data() {
      var checkEmail = (rule, value, callback) => {
        const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
        if (regEmail.test(value)) {
          return callback()
        }
        callback(new Error('请输入合法的邮箱'))
      }
      var checkMobile = (rule, value, callback) => {
        const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[013678]|18[0-9]|14[57])[0-9]{8}$/
        if (regMobile.test(value)) {
          return callback()
        }
        callback(new Error('请输入合法的手机号'))
      }
      return {
        addDialogVisible: false,
        editDialogVisible: false,
        settingDialogVisible: false,
        queryInfo: {
          query: '',
          pagenum: 1,
          pagesize: 5
        },
        info: [],
        total: 0,
        putInfo: {
          uId: 0,
          type: ''
        },
        postInfo: {
          username: '',
          password: '',
          email: '',
          mobile: ''
        },
        editInfo: {
          id: '',
          email: '',
          mobile: ''
        },
        settingInfo: {},
        rolesList: [],
        selectedRoleId: '',
        rules: {
          username: [{
              required: true,
              message: '请输入用户名',
              trigger: 'blur'
            },
            {
              min: 3,
              max: 10,
              message: '长度在 3 到 10 个字符',
              trigger: 'blur'
            }
          ],
          password: [{
              required: true,
              message: '请输入密码',
              trigger: 'blur'
            },
            {
              min: 6,
              max: 12,
              message: '长度在 6 到 12 个字符',
              trigger: 'blur'
            }
          ],
          email: [{
              required: true,
              message: '请输入邮箱',
              trigger: 'blur'
            },
            {
              validator: checkEmail,
              trigger: 'blur'
            }
          ],
          mobile: [{
              required: true,
              message: '请输入手机',
              trigger: 'blur'
            },
            {
              validator: checkMobile,
              trigger: 'blur'
            }
          ]
        }
      }
    },
    created() {
      this.initUserList()
    },
    methods: {
      //初始化
      async initUserList() {
        const {
          data: res
        } = await this.$http.get('users', {
          params: this.queryInfo
        })
        if (res.meta.status !== 200) {
          this.$message({
            showClose: true,
            message: '获取数据失败',
            type: 'error'
          })
        } else {
          this.info = res.data.users
          this.total = res.data.total
        }
      },
      handleSizeChange(val) {
        console.log(`每页 ${val} 条`);
        this.queryInfo.pagesize = val
        this.initUserList()

      },
      handleCurrentChange(val) {
        console.log(`当前页: ${val}`);
        this.queryInfo.pagenum = val
        this.initUserList()
      },
      //修改用户状态
      async userStateChange(userInfo) {
        const {
          data: res
        } = await this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`)
        if (res.meta.status !== 200) {
          this.$message({
            showClose: true,
            message: '修改数据失败',
            type: 'error'
          })
          userInfo.mg_state = !userInfo.mg_state
        } else {
          this.$message({
            showClose: true,
            message: '修改数据成功',
            type: 'success'
          })
        }
      },
      handleClose(done) {
        this.$confirm('确认关闭？')
          .then(_ => {
            done();
          })
          .catch(_ => {});
      },
      //清空添加用户对话框
      addClearDialog() {
        this.$refs.postInfoRef.resetFields()
      },
      //清空修改用户对话框
      editClearDialog() {
        this.$refs.editInfoRef.resetFields()
      },
      //清空分配角色对话框
      settingClearDialog() {
        this.selectedRoleId = '',
          this.settingInfo = {}
      },
      //添加用户
      addUser() {
        this.$refs.postInfoRef.validate(async valid => {
          if (!valid) {
            this.$message({
              showClose: true,
              message: '提交的数据非法',
              type: 'error'
            })
          } else {
            //提交数据
            const {
              data: res
            } = await this.$http.post('users', this.postInfo)
            if (res.meta.status !== 201) {
              this.$message({
                showClose: true,
                message: '添加用户失败',
                type: 'error'
              })
            } else {
              this.$message({
                showClose: true,
                message: '添加用户成功',
                type: 'success'
              })
              this.addDialogVisible = false
              this.addClearDialog()
              this.initUserList()
            }
          }
        })
      },
      //打开修改用户信息对话框，获取用户信息
      openEditUser(editForm) {
        this.editDialogVisible = true
        this.editInfo = editForm
      },
      //提交修改后的用户信息
      editUser() {
        this.$refs.editInfoRef.validate(async valid => {
          if (!valid) {
            this.$message({
              showClose: true,
              message: '提交的数据非法',
              type: 'error'
            })
          } else {
            //提交数据
            const {
              data: res
            } = await this.$http.put('users/' + this.editInfo.id, this.editInfo)
            if (res.meta.status !== 200) {
              this.$message({
                showClose: true,
                message: '修改用户失败',
                type: 'error'
              })
            } else {
              this.$message({
                showClose: true,
                message: '修改用户成功',
                type: 'success'
              })
              this.editDialogVisible = false
              this.editClearDialog()
              this.initUserList()
            }
          }
        })
      },
      //删除用户信息
      deleteUser(id) {
        this.$confirm('此操作将永久删除该用户信息, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          const {
            data: res
          } = await this.$http.delete('users/' + id)
          if (res.meta.status !== 200) {
            this.$message({
              showClose: true,
              message: '删除用户失败',
              type: 'error'
            })
          } else {
            this.$message({
              showClose: true,
              message: '删除用户成功',
              type: 'success'
            })
            this.initUserList()
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      //打开分配角色对话框，获取当前用户的角色信息
      async openSettingRole(role) {
        this.settingDialogVisible = true
        this.settingInfo = role
        const {
          data: res
        } = await this.$http.get('roles')
        if (res.meta.status !== 200) {
          this.$message({
            showClose: true,
            message: '获取所有角色失败',
            type: 'error'
          })
        } else {
          this.rolesList = res.data
        }
      },
      //点击按钮分配角色
      async saveRole() {
        if (!this.selectedRoleId) {
          this.$message({
            showClose: true,
            message: '请输入新角色',
            type: 'error'
          })
        } else {
          const {
            data: res
          } = await this.$http.put(`users/${this.settingInfo.id}/role`, {
            rid: this.selectedRoleId
          })
          if (res.meta.status !== 200) {
            this.$message({
              showClose: true,
              message: '设置角色失败',
              type: 'error'
            })
          } else {
            this.$message({
              showClose: true,
              message: '设置角色成功',
              type: 'success'
            })
            this.settingDialogVisible = false
            this.initUserList()
          }
        }
      }
    }
  }

</script>
<style lang="less" scoped>
  .box-card {
    margin-top: 15px;
    padding: 0;
    box-shadow: 0 1px 1px rgba(0, 0, 0, 0.1) !important;
  }

  .el-pagination {
    margin-top: 15px
  }

</style>
